package com.gallop.akka.util;

import akka.actor.ActorContext;
import akka.actor.Props;
import com.gallop.akka.SpringAkkaExtension;
import scala.collection.Iterator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class ActorContextUtil {

    /**
     * skip [ApplicationContext, Actor Class]
     *
     * @see SpringAkkaExtension.SpringExt#props(Class, Object...)
     */
    private static final int SKIP_ARG_NUM = 2;

    public static List<Object> getCustomArgs(ActorContext context) {
        if (context == null) {
            return null;
        }
        Props props = context.props();
        if (props.args().size() <= SKIP_ARG_NUM) {
            return null;
        }
        List<Object> ret = new ArrayList<>(props.args().size() - SKIP_ARG_NUM);
        Iterator<Object> iterator = props.args().iterator();
        int skip = 0;
        while (iterator.hasNext()) {
            Object arg = iterator.next();
            if (skip >= SKIP_ARG_NUM) {
                if (arg != null && arg.getClass().isArray()) {
                    ret.addAll(Arrays.stream(((Object[]) arg)).collect(Collectors.toList()));
                } else {
                    ret.add(arg);
                }
            }
            skip++;
        }
        return ret;
    }
}
